package org.xiaojl.config.easyui;

import java.util.ArrayList;
import java.util.List;

import org.xiaojl.common.Constants;
import org.xiaojl.modules.sys.entity.Organization;
import org.xiaojl.modules.sys.entity.SysResource;

public class EasyuiUtil {
	
	/**
	 * 将资源list转化为Treelist
	 */
	public static List<EasyUITree> resources2ResourceTree(List<SysResource> resList) {
		if(resList == null) return null;
    	List<EasyUITree> resultList = new ArrayList<EasyUITree>();
    	buildMenuTree(resList,resultList,null,true);
		return resultList;
	}

	/**
	 * 将资源list转化为MenuTreelist
	 */
    public static List<EasyUITree> resources2MenuTree(List<SysResource> resList) {
    	if(resList == null) return null;
    	List<EasyUITree> resultList = new ArrayList<EasyUITree>();
    	buildMenuTree(resList,resultList,null,false);
		return resultList;
	}
    
    private static List<EasyUITree> buildMenuTree(List<SysResource> resList, List<EasyUITree> resultList, Long pid, boolean hasBtn) {
    	if(resList == null) return null;
    	for(SysResource res : resList){
    		if(res != null 
    				&& (pid==null ? res.getPid()==null : res.getPid()!=null && res.getPid().compareTo(pid)==0) //pid=上级id
    				&& (hasBtn?true:res.getResourceType()==Constants.SysResource_MENU)){
    			EasyUITree tree = new EasyUITree();
    			tree.setId(res.getId());
    			tree.setText(res.getName());
    			tree.setIconCls(res.getIcon());
    			tree.setAttributes(res.getUrl().startsWith("/")?res.getUrl().substring(1, res.getUrl().length()):res.getUrl());
    			
    			//递归调用
    			List<EasyUITree> subList = new ArrayList<EasyUITree>();
    			buildMenuTree(resList,subList,res.getId(),hasBtn);
    			
    			tree.setChildren(subList);
    			resultList.add(tree);
    		}
    	}
    	return resultList;
    }

    /**
     * 部门list转换为easyUItree
     * @param list
     * @return
     */
	public static List<EasyUITree> organization2EasyUITree(List<Organization> list) {
		if(list == null) return null;
    	List<EasyUITree> resultList = new ArrayList<EasyUITree>();
    	buildOrganizationTree(list,resultList,null);
		return resultList;
	}
	private static void buildOrganizationTree(List<Organization> list,
			List<EasyUITree> resultList, Long pid) {
		if(list == null) return ;
		for(Organization o:list){
			if(o!=null 
					&& (pid==null?o.getPid()==null:(o.getPid()!=null && o.getPid().compareTo(pid)==0))){
				EasyUITree tree = new EasyUITree();
    			tree.setId(o.getId());
    			tree.setText(o.getName());
    			tree.setIconCls(o.getIcon());
    			
    			//递归调用
    			List<EasyUITree> subList = new ArrayList<EasyUITree>();
    			buildOrganizationTree(list,subList,o.getId());
    			tree.setChildren(subList);
    			
    			//添加到tree中
    			resultList.add(tree);
			}
		}
	}

	
}
